<template>
  <div class="table-box">
    <p v-if="fixedHead" class="header-box">{{fixedHead}}</p>
    <el-table :data="data" border   row-key="id" :row-style="showTr"  style="width: 99.8%"  tooltip-effect="dark" class="tree-table">
      <el-table-column v-for="(column, index) in columns"   :key="column.dataIndex"  :label="column.text" :min-width="firstWidth(column.dataIndex)"  :align="firstAlign(column.dataIndex)">
        <template slot-scope="scope" >       
          <span class="ishow" v-if="toggleIconShow(column.dataIndex,scope.row)" @click="toggle(scope.$index)">
                <small v-if="!scope.row._expanded" >显隐下级</small>
                <small v-if="scope.row._expanded" >显隐下级</small>
          </span>
          <div v-if="column.dataIndex=='url' || column.dataIndex=='piclink' " >   
              <span v-if="column.dataIndex=='url'">{{scope.row.url}}</span>
              <img v-else :src="$fnc.getImgUrl(scope.row.piclink)"  style="width:60px;"  />       
          </div>
          <div v-if="column.dataIndex=='description'">
              {{scope.row.description}}
          </div>
          <div v-if="column.dataIndex=='show'">
            <el-switch
                  class="zdySwith"
                  :width="82"
                  v-model="scope.row.show"
                  active-color="#1aad19"
                  inactive-color="#ffffff"
                  active-text="已开启"
                  inactive-text="已关闭"
                  active-value="1"
                  @change="handleSwitch($event,scope.row.id)"
                  inactive-value="0">
              </el-switch>
              <!-- <switchc style="font-size:13px;position: relative;top: 22%;" v-model="scope.row.show" @change="handleSwitch($event,scope.row.id)" text="已开启|已关闭"></switchc> -->
          </div>
          <div v-if="column.dataIndex=='created_time'">          
            {{scope.row.created_time | getTimeFormat}}
          </div>
          <div v-if="column.dataIndex=='title'">
            <span  v-for="(space, levelIndex) in scope.row._level" class="ms-tree-space"  :key="levelIndex"></span>
            <div style="display:inline-block;position:relative" >
              <div v-if="scope.row._level>0" class="up_img">
                <img  src="../../assets/img/jt.png" alt="">
              </div>
              <p  :class="[column.dataIndex=='title' ? 'text': '']">{{scope.row[column.dataIndex]}}</p>
              <div   v-if="toggleIcon(index,scope.row)">
                <p  class="font_p">{{scope.row._level+1 | toChinesNum}}{{"级栏目"}}{{scope.row.z == undefined ? "（下属分类0个）" : "（下属分类"+scope.row.z.length+"个）"}}</p>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" v-if="treeType === 'normal'">
        <template slot-scope="scope">
          <el-button  :loading='$store.state.isLoading' type="primary" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button  :loading='$store.state.isLoading' type="danger"  size="mini" @click="showHandledel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import Sortable from 'sortablejs'
import MSDataTransfer from '../../assets/js/dataTranslate.js';
import switchc from "@/components/currency/Swich.vue"
export default {
  props: {
    treeStructure: {
      type: Boolean,
      default: true
    },
    columns: {
      type: Array,
      default: () => []
    },
    dataSource: {},
    treeType: {
      type: String,
      default: 'normal'
    },
    defaultExpandAll: {
      type: Boolean,
      default: true

    },
    fixedHead: {
      type: String,
      default: ''
    },
    fixed: {
      type: Boolean,
      default: true
    },

    btnList: {
      type: Array,
      default: () => ([])
    },
    operatWidth: {
      type: Number,
      default: 300
    },
    xy:{
      type:Number,
      default:0
    }
  },
  data() {
    return {
      n:0,
      da:"",
      starIndex:"",
      endIndex:"",
      list:"",
      is_ex:[]
      
    }
  },
  computed: {
    data() {
      if (this.treeStructure) {
        let data = MSDataTransfer.treeToArray(this.dataSource, null, null, this.defaultExpandAll)
        this.da=data;
        return data
      }
      return this.dataSource
    },
  },
  methods: {
    showTr(rows, index) {
      let row = rows.row
      let show = (row._parent ? (row._parent._expanded && row._parent._show) : true)
      row._show = show
      return show ? '' : 'display:none;'
    },
    toggle(trIndex) {
      let record = this.data[trIndex]
      record._expanded = !record._expanded
      this.is_ex[trIndex]=record._expanded
    },
    spaceIconShow(index) {
      if (this.treeStructure && index === 0) {
        return true
      }
      return false
    },
    toggleIcon(index, record){
      if (this.treeStructure && (index === 0 || index === 1)) {
        return true 
      }
      return false
    },
    toggleIconShow(index, record) {

      if (this.treeStructure && index === "" && record.z && record.z.length > 0) {
        return true
      }
      return false
    },
    firstWidth(index) {
      if (index === "piclink") {
        return '80'
      } else if(index === "title"){
        return '200'
      }else{
        return "150"
      }
    },
    firstAlign(index) {
      if (index === "title") {
        return 'left'
      } else{
        return 'center'
      }
    },
    showEditDialog(row){
      this.$emit("updataMenu",row);
    },
    showHandledel(index){

      this.$emit("delMenu",index);
    },
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody');
      const _this = this;
      var aa=new Sortable(tbody, {
                group: "",  // or { name: "...", pull: [true, false, clone], put: [true, false, array] }
                sort: true,  // sorting inside list
                delay: 0, // time in milliseconds to define when the sorting should start
                disabled: false, // Disables the sortable if set to true.
                store: null,  // @see Store
                animation: 150,  // ms, animation speed moving items when sorting, `0` — without animation
                // handle: '',  // Drag handle selector within list items
                // filter: ".el-input",  // Selectors that do not lead to dragging (String or Function)
                // draggable: '.items>div',  // Specifies which items inside the element should be draggable
                chosenClass: "sortable-chosen",  // Class name for the chosen item
                dragClass: "sortable-drag",  // Class name for the dragging item
                // dataIdAttr: 'data-id',

                forceFallback: false,  // ignore the HTML5 DnD behaviour and force the fallback to kick in

                fallbackClass: false,  // Class name for the cloned DOM Element when using forceFallback
                fallbackOnBody: false,  // Appends the cloned DOM Element into the Document's Body
                fallbackTolerance: 0, // Specify in pixels how far the mouse should move before it's considered as a drag.        

                // scroll: true, // or HTMLElement
                // scrollFn: function(offsetX, offsetY, originalEvent) {  }, // if you have custom scrollbar scrollFn may be used for autoscrolling
                // scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
                // scrollSpeed: 10, // px

        onStart: function (evt) { 
            _this.list = $(".el-table__body-wrapper tbody>tr");
        },
        onChange({ newIndex, oldIndex }) {
          if(!(!(_this.da[oldIndex]._level != _this.da[newIndex]._level) && (_this.da[oldIndex].parent_id == _this.da[newIndex].parent_id))){
              $(".el-table__body-wrapper tbody").html(_this.list);
          }else{
                const currRow = _this.da.splice(oldIndex, 1)[0];
                _this.da.splice(newIndex, 0, currRow);
          }
         
        },
        onEnd({ newIndex, oldIndex }) {
            var data={};
            var sort_str =[];
            var parent_id  =_this.da[newIndex].parent_id;
              for(var i in _this.da){
                  if(_this.da[i].parent_id==_this.da[newIndex].parent_id){
                      sort_str.push(_this.da[i].id);
                  }
              }
              data.sort_str=sort_str.join("@");
              data.parent_id=parent_id;
              _this.$emit("getSort",data);

        }
      })
    },
    handleSwitch(show,id){
      this.$emit("handSwitch",{id,show});
    }

  },
  mounted(){
    this.rowDrop();
    console.log(1)
    for(var i in this.data){
            this.data[i]._expanded=!this.data[i]._expanded
            this.is_ex.push(this.data[i]._expanded)
    }
  },
  watch:{
    xy(val){
      this.is_ex=[];
        for(var i in this.data){
            this.data[i]._expanded=!this.data[i]._expanded
            this.is_ex.push(this.data[i]._expanded)
        }
    },
    data(val,val2){
        for(var i in this.data){
            this.data[i]._expanded=this.is_ex[i];
        }

      
    }
  },
  components:{
    switchc
  }
}

</script>
<style scoped>
.table-box {
  width: 100%;
  height: 100%;
}

.header-box {
  padding: 8px 0;
  margin: 0;
  text-align: center;
  font-weight: bold;
}

.ms-tree-space {
  position: relative;
  top: 1px;
  display: inline-block;
  font-family: 'Glyphicons Halflings';
  font-style: normal;
  font-weight: 400;
  line-height: 1;
  width: 50px;
  height: 14px;
}
.ms-tree{
 /* position: relative; */
  /* top: 1px; */
  display: inline-block;
  font-family: 'Glyphicons Halflings';
  font-style: normal;
  font-weight: 400;
  line-height: 1;
  width: 30px;
  height: 14px;

}
.ms-tree-space::before {
  content: ""
}

table td {
  line-height: 26px;
}

.button {
  font-size: 20px;
  cursor: pointer;
}

.firstWidth {
  min-width: 150px;
}
.tree-table .el-table__body-wrapper {
  overflow-y: auto;
}

.el-icon-circle-plus,
.el-icon-remove {
  color: #409EFF;
}
.yi {
  padding-left: 35px;
}

.yi,
.er,
.san,
.caozuo {
  line-height: 1.1;
  font-size: 12Px;
}
.er,
.san{
  background: url("../../assets/img/jt.png") no-repeat;
}
.er {
  padding-left: 100px;
  background-position: 15% center;
}
.san {
  padding-left: 180px;
   background-position: 32% center;
}
.text {
  color: #1082ef;
  text-align: left;
}
.text_item {
  color: #979797;
  margin-top: 10px;
}
.xiaji {
  background: #5cb85c;
  font-size: 13px;
  padding: 5px 14px;
  color: #fff;
  border-radius: 2px;
}
.caozuo {
  padding-left: 50px;
}
.up_img{
  position: absolute;
  top: 25%;
  left: -15%;
}
.font_p{
  font-size: 13px;
  color: #b3aead;
}
</style>
